#!/usr/bin/perl

use strict;
use lib qw(lib);

use CPANPLUS::Backend;
use CPANPLUS::Module;
use HTML::Template;
use local::lib;

my $output;

use CGI;
use CGI::Carp qw(fatalsToBrowser);

$| = 1;

my $cgi   = CGI->new();

print $cgi->header('text/html; charset=utf-8');

if (my $module = $cgi->param('module')) {
  
  render({ module => $module }, 'install_top',);
  install($module);
  render({ }, 'install_bottom',);
}
else {
  render(undef,'search');
}

sub render {
  my $args = shift;
  my $stage = shift;
  my $template = HTML::Template->new(
                  filename => "./content/${stage}.html",
                  die_on_bad_params => 0);
  $template->param($args);
  print $template->output;
}

sub install { 
  my $name = shift;

  my $cb   = CPANPLUS::Backend->new;
  $cb      = set_conf($cb);
  my @res  = $cb->search(type=> 'module', allow => [qr/^$name$/]);
  my $output = $res[0]->install(verbose => 1);
  return $output;
}

sub set_conf {
  my $cb  = shift;
  $CPANPLUS::Error::ERROR_FH = *STDOUT;
  $cb->configure_object->set_program('sudo' => '');
  return $cb;
}

__END__

=head1 NAME

install.pl - fires off a CPANPLUS install routine and shows the output

=head1 TODO

 * Verify we have a module name to install to start with
 * Check the module name is sane
 * Capture the output of CPAN::Module->install and feed it sanely to outpit

That last one has had me vexed for a while now. Any help greatfully received.

=head1 FUNCTIONS

=over 4

=item set_conf

Automatically sets the PERL5LIB environment variable, 
makemaker and lib CPANPLUS. Requires a CPANPLUS::Backend object which
it returns on completion.

=item render

Parses an HTML template and prints it to STDOUT. Takes two arguments:

 args - hash ref of variables to add as params to the template
 stage - the filename of the template to use (without .html extension)

=item install

Installs a CPAN module. Takes one argument - the module name. Prints
the results of the installation to STDOUT.

=back

=cut